<template>
	<view class="main" style="background-color: #e4ecf7;min-height: 100vh;">
		<!-- 地址栏 -->
			<uni-list-item :title="address.detail" :note="address.detail1" showArrow
				thumb="/static/icons/gps.png"
				thumb-size="base"   class="shadowed-item" link /> 
		<!-- 商品卡片 -->
         
		 <view class="cart">
		   <view class="order-container" v-for="order in list" :key="order.orderId">
		     <view class="order-header">
		       订单号：{{ order.orderId }} 
		     </view>
		     <view class="item-list">
		       <view class="item" v-for="item in order.items" :key="item.cartProductId">
		         <view class="left">
		<view class="text-above-img">{{ item.cartProductName }}<u-icon name="arrow-right"></u-icon></view>
		           <image :src="item.cartImgUrl" class="img"></image>
		         </view>
		         <view class="center">
		           <view class="name">{{ item.cartProductColor }}</view>
		           <view class="size">{{ item.cartProductAge }}</view>
		           <view class="count">数量 x {{ item.cartProductNum }}</view>
		         </view>
		 		  <!-- 右侧内容 -->
		         <view class="right">
		 				<view class="price" style="color: red;margin-top: 10rpx;">
		 				  ￥{{item.cartCurrentPrice}}元
		 				</view>
		         </view>
		       </view>
		     </view>
		   </view>
		 </view>
		 
		 <!-- 配送时间选择 -->
		 <view class="changeInfo">
      <picker :range="deliveryTimeChang" v-model="deliveryTimeIndex" @change="bindTimeChange">
        <view class="text-box">
          <view class="left">配送时间</view>
          <view class="iconfont iconchangyongicon- icon-box"></view>
          <uni-icons type="right" size="22" style="float: right;margin-right: 10rpx;"></uni-icons>
          <view class="right" style="color: #868686">{{deliveryTimeChang[deliveryTimeIndex]}}</view>
        </view>
      </picker>
			<!-- 订单备注 -->
			<navigator  url="#" class="text-box" @tap="showInputDialog">
				<view class="left">订单备注</view>
				<view class="iconfont iconchangyongicon- icon-box"></view>
				<view class="right" style="color: #8f8f8f;">{{remark}}</view>
			</navigator>
			</view>
		 <!-- 底部 -->
        <view class="tabbar">
            <view class="totalPrice">
                总价:￥{{list[0].total}}元
            </view>
            <view class="submitOrder" @tap="submitOrder(list[0].total)">
                提交订单
            </view>
        </view>
	</view>				
</template>

<script>
	import {
		store
	} from '@/uni_modules/uni-id-pages/common/store.js';
	import {
		get,
		post,
		setToken
	} from '@/utils/api.js';
	export default {
		components:{
		},
		data() {
			return {
				sum:'',
				list: [
				  {
				    orderId: '',
				    items: [],
				    orderState: ''
				  }
				],
				count:0,
				remark:'选填,建议留言前先和商家沟通',
      deliveryTimeChang: ['时间不限（周一至周日）', '工作日（周一至周五）', '周末'],
      deliveryTimeIndex: 0, // 默认选中第一个选项
				index: 0,
				address:{},
				      // 初始状态
				      isManaging: true,
				      // 数据绑定
				      text: '管理',
					  iconType:'compose',
					  isShow:true
			}
		},
		onLoad() {
		},
		 computed: {
		    deliveryTime() {
		      return this.deliveryTimeChang[this.deliveryTimeIndex];
			  
		    },
		  },
		created() {
			this.getMyOrder()
			this.getMydefultAddress()
			if(uni.getStorageSync('waitOrderId'))
			{
				console.log(uni.getStorageSync('waitOrderId'))
			}
			uni.getStorageSync('shopData')
			console.log(uni.getStorageSync('shopData'))
		},
		beforeDestroy() {
			 uni.setStorageSync('oid',uni.getStorageSync('uid'))
			// uni.setStorageSync('ordersNote',this.remark)
			// uni.setStorageSync('ordersStatus',this.deliveryTimeChang[this.count])
			
			uni.removeStorageSync('shopData')
			uni.removeStorageSync('waitOrderId')
			uni.removeStorageSync('uid')
			
		},
		methods: {
getMyOrder() {
	console.log(uni.getStorageSync('uid'))
    post('/order/getOrderByOid',
    {
        oid:uni.getStorageSync('uid')
    }, {
        needToken: true, 
        success: (res) => {
            if (res.statusCode === 200) {
                const ordersData = res.data.data;
                console.log(res.data.data)
                // 创建一个 Map 来按 oid 分组数据
                const groupedOrders = ordersData.reduce((acc, order) => {
                    if (!acc.has(order.oid)) {
                        acc.set(order.oid, []);
                    }
                    acc.get(order.oid).push(order);
                    return acc;
                }, new Map());
                
                // 重新构建数据结构，并计算总价
                const formattedList = Array.from(groupedOrders.entries()).map(([oid, items]) => {
                    const total = items.reduce((acc, item) => acc + item.ordersProdNumber * item.ordersCurrentPrice, 0);
					console.log(total)
                    return {
                        orderId: oid,
                        items: items.map(item => ({
                            cartProductId: item.ordersProductId,
                            cartProductName: item.ordersProductName,
                            cartProductColor: item.ordersProductColor,
                            cartProductAge: item.ordersProductAge,
                            cartProductGender: item.ordersProductGender,
                            cartProductNum: item.ordersProductNum,
                            cartUser: item.ordersUser,
                            cartImgUrl: item.cartImgUrl,
                            cartCurrentPrice: item.ordersCurrentPrice,
                            cartCreatetime: item.ordersCreatetime
                        })),
                        orderState: items[0].cartStatus, // 假设每个 oid 对应的 cartStatus 是一致的
                        total: total // 添加总价
                    };
                });

                this.list = formattedList;
            }
        }
    });
},
		getMydefultAddress() {
		post('/address/default',
		{
         username:store.userInfo.username
		}, {
		  needToken: true, 
			success: (res) => {
			if (res.statusCode === 200) {
               this.address = res.data
               this.address.detail = this.address.addressCity + ' ' +  this.address.addressArea
               this.address.detail1 = this.address.addressHost + ' ' +  this.address.addressHostTel
			}
		  }
		}); 	
		},
			submitOrder(price) { // 提交订单
			uni.setStorageSync('price',price)
			uni.setStorageSync('oid',uni.getStorageSync('uid'))
			this.updateOrder()
			 uni.navigateTo({
			url:'/pages/payment/payment'
		   })   
			},
			showInputDialog() {
				uni.showModal({
				        title: '留言',
				        content: '',
				        editable:true,//是否显示输入框
						placeholderText:'留言内容',//输入框提示内容
				        confirmText: '确认',
				        cancelText: '取消',
				        success: (res) => {
				          if (res.confirm) {
							  this.remark = res.content
				          }
				        } 
				      });
			},
			updateOrder() {
				if(this.remark === '选填,建议留言前先和商家沟通')
				 this.remark = ''
				 // console.log(this.remark)
				 // console.log(this.deliveryTimeChang[this.count])
			post('/order/updateOrder',
			{
			 oid:uni.getStorageSync('uid'),
			 ordersNote:this.remark,
			 ordersPosttime:this.deliveryTimeChang[this.count],
			 
			}, {
			  needToken: true, 
				success: (res) => {
				if (res.statusCode === 200) {
                 console.log('订单状态更新成功！')
				}
				else
				console.log(res.data)
			  }
			});	
			},
             gotoAddress(){
				 uni.navigateTo({
				 	url:'/pages/DelAddress/DelAddress'
				 })
			 },
				bindTimeChange(e) {
				  this.deliveryTimeIndex = e.detail.value;
				  this.count =  this.deliveryTimeIndex
				},
		}
	}
</script>

<style lang="scss" scoped>
	.loan_box{
		background-color: #fff;
		width: 100%;
		margin: 20rpx auto;
		border-radius: 10rpx;
		padding: 10rpx 20rpx;
		padding-bottom: 20rpx;
		box-sizing: border-box;
		.loan_title_box{
			display: flex;
			align-items: center;
			padding-top: 6rpx;
			.title{
				font-size: 30rpx;
			}
			.link{
				margin-left: auto;
				color: #797979;
				font-size: 20rpx;
			}
		}
		.loan_list{
			margin-top: 30rpx;
			.list_item{
				padding: 0 10rpx;
				border-bottom: 1px solid #e9e9e9;
				margin-top: 20rpx;
				.item_head{
					display: flex;
					align-items: center;
					.pic{
						height: 100rpx;
						width: 100rpx;
						border-radius: 50%
					}
					.loan_info{
						margin-left: 20rpx;
						.name{
							color: #797979;
							font-weight: 600;
						}
						.date{
							color: #797979;
							margin-top: 6rpx;
						}
					}
					.join_btn{
						background-color: #ffffff;
						color: #fff;
						margin-left: 150rpx;
						padding: 6rpx 30rpx;
						border-radius: 30rpx;
						font-size: 28rpx;
					}
				}
				.item_bottom{
					display: flex;
					margin-top: 20rpx;
					padding-bottom: 14rpx;
					width: 100%;
					.bottom_item{
						flex: 1;
						display: flex;
						flex-direction: column;
						align-items: flex-start;
						justify-content: center;
						font-size: 26rpx;
						.names{
							color: #797979;
						}
						.amount{
							color: #ff0548;
							margin-top: 6rpx;
							font-weight: 600;
						}
					}
				}
			}
		}
	}
	.foot_line{
		display: flex;
		align-items: center;
		justify-content: center;
		padding-bottom: 20rpx;
		color: #5f5f5f;
		.line{
			width: 200rpx;
			border-bottom: 1px solid #5f5f5f;
		}
	}
	.text-box{
		width: 100%;
		height: 52px;
		line-height: 52px;
	}
	.left{
		float: left;
		font-size: 15px;
		margin-left: 50rpx;
		color: #000000;
	}
	.right{
		float: right;
		font-size: 15px;
		margin-right: 50rpx;
		color: #000000;
	}
	.icon-box{
		float: right;
		font-size: 15px;
		color:  #999999;
		width: 10px;
	}
	.changeInfo {
	  width: 100%;
	  height: 100%;
	  background-color: #ffffff;
	  background-position: center center;
	  background-repeat: no-repeat;
	  background-size: cover;
	  /* 添加阴影效果 */
	box-sizing: border-box;
	  /* 添加层次感，这里假设你想让该表单在其他内容之上 */
	  position: relative;
	  z-index: 5; /* 根据需要调整z-index的值，确保它高于周围元素 */
	}
	// 底部导航
	.tabbar {
	    width: 100%;
	    height: 120rpx;
	    background-color: #f3f3f3;
	    position: fixed;
	    bottom: 0rpx;
	    display: flex;
	    align-items: center;
	    justify-content: space-around;
	    border-radius: 8% 8%;
	
	    .totalPrice {
	        font-size: 32rpx;
	        color: #3E3E3E;
	        letter-spacing: 2.29rpx;
	        color: red;
	    }
	
	    .submitOrder {
	        width: 208rpx;
	        height: 80rpx;
	        background: #ff5500;
	        border-radius: 14rpx;
	        border-radius: 14rpx;
	        font-size: 36rpx;
	        color: #FFFFFF;
	        letter-spacing: 2.57rpx;
	        display: flex;
	        align-items: center;
	        justify-content: center;
	    }
	}
	.cart {
	  width: 750rpx;
	  margin: -11rpx auto 20rpx;
	  background: #ffffff;
	
	  .order-container {
	    width: 750rpx;
	    background: #f9f9f9;
	    box-shadow: 0 8rpx 16rpx 0 rgba(83, 66, 49, 0.08);
	    border-radius: 24rpx;
	    margin-top: 32rpx;
	    padding: 16rpx;
	
	    .order-header {
	      font-size: 20rpx;
	      font-weight: bold;
	      color: #3E3E3E;
	      margin-bottom: 16rpx;
	    }
	
	    .item-list {
	      display: flex;
	      flex-direction: column;
	      gap: 16rpx;
	
	      .item {
	        display: flex;
	        justify-content: space-between;
	        align-items: center;
	
	        .left {
	
	
	          .text-above-img {
	            width: 100%;
	          }
	
	          .img {
	            width: 178rpx;
	            height: 136rpx;
	            margin-bottom: 10rpx;
	            border-radius: 8%;
	          }
	        }
	
	        .center {
	          width: 170rpx;
	
	          .name {
	            font-size: 26rpx;
	            color: #3E3E3E;
	            white-space: nowrap;
	            text-overflow: ellipsis;
	            overflow: hidden;
	          }
	
	          .size,
	          .count {
	            font-size: 22rpx;
	            color: #8D8D8D;
	          }
	        }
	
	        .right {
	          .price {
	            margin-top: 0;
	            font-size: 26rpx;
	            margin-left: 10rpx;
				text-align: center;
	          }
	
	          .update-count {
	            margin-top: 0;
	            display: flex;
	
	            .mini-btn {
	              width: 120rpx;
	              height: 50rpx;
	              background: #F1ECE7;
	              border-radius: 21.6rpx;
	              color: red;
	              font-size: 16rpx;
	              display: flex;
	              align-items: center;
	              justify-content: center;
	            }
	          }
	        }
	      }
	    }
	  }
	}
</style>